package dao;

import entity.Veterinarian;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

public class VeterinarianDAO extends DAO<Veterinarian> {

    public VeterinarianDAO(EntityManagerFactory emf) {
        super(emf);
    }

    @Override
    protected Root from(CriteriaQuery cq) {
        return cq.from(Veterinarian.class);
    }

    @Override
    protected boolean exists(Veterinarian object) {
        EntityManager entityManager = getEntityManager();
        Query query = entityManager.createQuery("SELECT v FROM Veterinarian v WHERE v.name=:name AND v.lastname=:lastname");
        query.setParameter("name", object.getName());
        query.setParameter("lastname", object.getLastname());
        
        return !query.getResultList().isEmpty();
    }
    
    @Override
    public void edit(Veterinarian object) throws Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            //Remove all the appointments related to this vet so only the ones currently being used are persisted
            Query appointmentQuery = em.createQuery("DELETE FROM Appointment a WHERE a.veterinarian.id = :id");
            appointmentQuery.setParameter("id", object.getId());
            appointmentQuery.executeUpdate();
            //Save the vet
            em.merge(object);
            em.getTransaction().commit();
            //Persist the current appointments
            AppointmentDAO appointmentDAO = new AppointmentDAO(Persistence.createEntityManagerFactory("HPVA"));
            appointmentDAO.create(object.getAppointments());
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }
    
    public List findByName(String[] names) {
        EntityManager entityManager = getEntityManager();
        Query query = entityManager.createQuery("SELECT v FROM Veterinarian v where v.name IN :names OR v.lastname IN :names");
        query.setParameter("names", Arrays.asList(names));
        
        return query.getResultList();
    }

}
